package com.google.project.client.Director;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.UsersDTO;

public class DRTProjectList extends Composite {

	@UiField(provided=true) CellTable<ProjectDTO> ctbProjectList = new CellTable<ProjectDTO>();
	@UiField ListBox cboStatus;
	@UiField TextBox txtProjectName;
	@UiField Button searchBtn;
	@UiField SimplePager pager;
	@UiField ListBox cboPm;
	private static final Binder binder = GWT.create(Binder.class);
	
	interface Binder extends UiBinder<Widget, DRTProjectList> {
	}

	
	//_____________________________Common variable_____________________________
	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);
	private final UsersServiceAsync userService = GWT.create(UsersService.class);
	List<ProjectDTO> listProject = new ArrayList<ProjectDTO>();
	List<UsersDTO> userList =new ArrayList<UsersDTO>();
	List<ProjectDTO> pjList = new ArrayList<ProjectDTO>();
	private int status;
	
	//End__________________________Common variable_____________________________
	
	//________________________________Contructor_______________________________
//	public DRTProjectList() {
//		initWidget(binder.createAndBindUi(this));
//	}



public DRTProjectList() {
	
	initWidget(binder.createAndBindUi(this));
	userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
		
		@Override
		public void onSuccess(List<UsersDTO> result) {
		userList = result;
		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {
			
			@Override
			public void onSuccess(List<ProjectDTO> projectList) {
				listProject = projectList;
				fillCbStatus();
				initTable();
				search();
			}
			
			@Override
			public void onFailure(Throwable caught) {
			}
		});
			
		}
		
		@Override
		public void onFailure(Throwable caught) {
		}
	});
}
//End_____________________________Contructor_______________________________

public DRTProjectList(int _status) {
	initWidget(binder.createAndBindUi(this));
	this.status = _status;
	userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
		
		@Override
		public void onSuccess(List<UsersDTO> result) {
		userList = result;
		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {
			
			@Override
			public void onSuccess(List<ProjectDTO> projectList) {
				listProject = projectList;
				fillCbStatus(status);
				initTable();
				searchProject(status);
			}
			
			@Override
			public void onFailure(Throwable caught) {
			}
		});
			
		}
		
		@Override
		public void onFailure(Throwable caught) {
		}
	});
}

//_____________________________Common function_____________________________
/*
 * Fill data to cell table - ctbProjectList
 */
public void bindData() {

	projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

		@Override
		public void onSuccess(List<ProjectDTO> result) {
			listProject =result;
			loadData(result);
		}

		@Override
		public void onFailure(Throwable caught) {
			Window.alert("Có lỗi trong quá trình Tải thông tin!");
		}
	});
}

public void initTable() {
	
	TextColumn<ProjectDTO> stt = new TextColumn<ProjectDTO>() {
		@Override
		public String getValue(ProjectDTO project) {
			return project.getIndex()+"";
		}
	};
	//Cot Ten du an - hyberlink ket noi voi bang Chi tiet
	Column<ProjectDTO, String> projectNameColumn = new Column<ProjectDTO, String>(
			new ClickableTextCell()) {
		@Override
		public String getValue(ProjectDTO object) {
			return object.getProjectName();
		}
	};
	projectNameColumn
			.setFieldUpdater(new FieldUpdater<ProjectDTO, String>() {
				@Override
				public void update(int index, ProjectDTO project,
						String value) {
					//Chuyen sang bang chi tiet du an
					DRTEntrypoint.get().DRTProjectDetail(project.getProjectID());
				}
			});
	
	//Cot Ten du an
	TextColumn<ProjectDTO> projectCodeColumn = new TextColumn<ProjectDTO>() {
		@Override
		public String getValue(ProjectDTO project) {
			return project.getProjectCode();
		}
	};
	//Cot Ten du an
	TextColumn<ProjectDTO> complete = new TextColumn<ProjectDTO>() {
		@Override
		public String getValue(ProjectDTO project) {
			return project.getComplete()+"%";
		}
	};
	//Cot Quan tri du an
	TextColumn<ProjectDTO> pmColumn = new TextColumn<ProjectDTO>() {
		@Override
		public String getValue(ProjectDTO project) {
			return project.getAccountName();
		}
	};
	
	//Cot Ngay bat dau 
	TextColumn<ProjectDTO> startDateColumn = new TextColumn<ProjectDTO>() {
		@Override
		public String getValue(ProjectDTO project) {
			return CommonFuntion.convertToDate(new Date(project.getStartDate()));
		}
	};
	
	//Cot Ngay ket thuc
	TextColumn<ProjectDTO> dueDateColumn = new TextColumn<ProjectDTO>() {
		@Override
		public String getValue(ProjectDTO project) {
			if(project.getStatus()==0||project.getStatus()==1)
			{
				return CommonFuntion.convertToDate(new Date( project.getDueDate()));
			}
			return CommonFuntion.convertToDate(new Date( project.getFinishDate()));
		}
	};
	
	TextColumn<ProjectDTO> statusColumn = new TextColumn<ProjectDTO>() {
		@Override
		public String getValue(ProjectDTO project) {
			int status = project.getStatus();
			String _status = "";
			if(status == 0){
				_status += "Dự án mới";
			}else if(status == 1){
				_status += "Đang tiến hành";
			}else if(status == 2){
				_status += "Đã hoàn thành";
			}
			if(status==3)
			{
				return "Ngừng thực hiện";
			}
			return _status;
		}
	};
	
	//Setup width
	ctbProjectList.setWidth("100%", true);
	ctbProjectList.setPageSize(5);
	ctbProjectList.setPageStart(0);
	ctbProjectList.addColumn(stt, "STT");
	ctbProjectList.setColumnWidth(stt, 5.0, Unit.PCT);
	projectNameColumn.setCellStyleNames("celltable");
	ctbProjectList.setStyleName("ttable");
	ctbProjectList.addColumn(projectCodeColumn, "Mã dự án");
	ctbProjectList.addColumn(projectNameColumn, "Tên dự án");
	ctbProjectList.setColumnWidth(projectNameColumn, 25.0, Unit.PCT);
	
	ctbProjectList.getColumn(ctbProjectList.getColumnIndex(projectNameColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

	ctbProjectList.addColumn(complete, "Hoàn thành");
//	ctbProjectList.addColumn(pmColumn, "Quản trị dự án");
//	ctbProjectList.setColumnWidth(pmColumn, 19.0, Unit.PCT);
	
	ctbProjectList.addColumn(startDateColumn, "Ngày bắt đầu");
	ctbProjectList.getColumn(ctbProjectList.getColumnIndex(startDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
	
	ctbProjectList.addColumn(dueDateColumn, "Ngày kết thúc");
	ctbProjectList.getColumn(ctbProjectList.getColumnIndex(dueDateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
	
	ctbProjectList.addColumn(statusColumn,"Trạng thái");
}
/*
 * @param projectList
 */
public void loadData(List<ProjectDTO> projectList) {
	
	// SimplePager
	pager.setDisplay(ctbProjectList);
	pager.setPageSize(5);
	
	// Create a data provider.
	ListDataProvider<ProjectDTO> dataProvider = new ListDataProvider<ProjectDTO>();

	// Connect the table to the data provider.
	dataProvider.addDataDisplay(ctbProjectList);

	// Add the data to the data provider, which automatically pushes it to
	// the widget
   int count =1;
	List<ProjectDTO> list = dataProvider.getList();
	for (ProjectDTO project : projectList) {
		project.setIndex(count);
		count++;
			list.add(project);
	}

}

/***
 * Fix data to cboStatus
 */
public void fillCbStatus() {
	cboStatus.addItem("---Tất cả---", "-1");
	cboStatus.addItem("Dự án mới", "0");
	cboStatus.addItem("Đang tiến hành", "1");
	cboStatus.addItem("Đã hoàn thành", "2");
	cboStatus.addItem("Ngừng thực hiện", "3");
	cboStatus.setSelectedIndex(2);
	
	cboPm.addItem("---Tất cả---", "-1");
	for(UsersDTO user:userList)
	{
		if(user.getUserGroup()!=null&&user.getUserGroup()==2)
		{
		cboPm.addItem(user.getUserName()+ " ("+user.getFullName()+")",user.getUserId());
		}
	}
	cboPm.setSelectedIndex(0);
}

public void fillCbStatus(int status) {
	cboStatus.addItem("---Tất cả---", "-1");
	cboStatus.addItem("Dự án mới", "0");
	cboStatus.addItem("Đang tiến hành", "1");
	cboStatus.addItem("Đã kết thúc", "2");
	int index = 0;
	if(status == 0) {
		index = 1;
	} else if(status == 1) {
		index = 2;
	} else if(status == 2) {
		index = 3;
	}
	cboStatus.setSelectedIndex(index);
	
	cboPm.addItem("---Tất cả---", "-1");
	for(UsersDTO user:userList)
	{
		if(user.getUserGroup()!=null&&user.getUserGroup()==2)
		{
		cboPm.addItem(user.getUserName()+ " ("+user.getFullName()+")",user.getUserId());
		}
	}
	cboPm.setSelectedIndex(0);
}


public void search()
{
	List<ProjectDTO> searchData = new ArrayList<ProjectDTO>();
	Boolean check = true;
	for(ProjectDTO project : listProject)
	{
		if(!cboPm.getValue(cboPm.getSelectedIndex()).equals("-1"))
		{
			check =check&&(project.getUserId().equals(cboPm.getValue(cboPm.getSelectedIndex())));
			
		}
		
		if(!cboStatus.getValue(cboStatus.getSelectedIndex()).equals("-1"))
		{
			check =check&&(cboStatus.getValue(cboStatus.getSelectedIndex()).equals(project.getStatus()+""));
		}
		if(txtProjectName.getValue().trim()!=null&&!txtProjectName.getValue().trim().equals(""))
		{
			check = check&&(project.getProjectName().contains(txtProjectName.getValue().trim()));
		}
		if(check)
		{
			searchData.add(project);
		
		}
		check = true;
	}
	loadData(searchData);
	}
//End__________________________Common function_____________________________

//Ham search project by status -> dung cho Homepage
public void searchProject(final int status) {
	for(ProjectDTO pjDTO : listProject) {
		if(pjDTO.getStatus() == status) {
			pjList.add(pjDTO);
		}
	}
	loadData(pjList);
}


@UiHandler("searchBtn")
void onSearchBtnClick(ClickEvent event) {
	search();
	}
}